package com.imooc.miaosha.util;

import com.alibaba.fastjson.TypeReference;
import com.imooc.miaosha.common.Const;
import com.imooc.miaosha.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Slf4j
public class SessionRefreshFilter  {


    public void init(FilterConfig filterConfig) throws ServletException {

    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        log.info("=========={}========", servletRequest.getRequestURI());

//        if (Const.FILTER_URI.TO_LOGIN.equals(servletRequest.getRequestURI())||
//                Const.FILTER_URI.DO_LOGIN.equals(servletRequest.getRequestURI())||
//                servletRequest.getRequestURI().contains(Const.FILTER_URI.JS_EXTEND)||
//        servletRequest.getRequestURI().contains(Const.FILTER_URI.CSS_EXTEND)||
//        servletRequest.getRequestURI().contains(Const.FILTER_URI.ICON_EXTEND)){
//            chain.doFilter(request,response);
//        }
//


        String loginToken = CookieUtil.readCookie(servletRequest);
        if (loginToken == null) {
            chain.doFilter(request, response);
        } else {
            String userJson = JedisUtil.get(Const.LOGIN_TOKEN_PREFIX, loginToken);
            UserDTO userDTO = JsonUtil.String2Obj(userJson, new TypeReference<UserDTO>() {
            });
            if (userDTO != null) {
                JedisUtil.expire(Const.LOGIN_TOKEN_PREFIX, loginToken, 60 * 30);
            }
            chain.doFilter(request, response);
        }
    }


    public void destroy() {

    }
}
